package com.wxb.controller;

import com.alibaba.fastjson.JSONObject;
import com.wxb.common.core.web.domain.AjaxResult;
import com.wxb.common.security.utils.SecurityUtils;
import com.wxb.domain.MallFeedbackEntity;
import com.wxb.service.IMallFeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;

/**
 * @Date 2025-05-30 15:36
 * @Version 1.0
 * @Description
 * @ClassName MallFeedbackController
 **/
@RestController
@RequestMapping("/feedback")
public class MallFeedbackController {
    @Autowired
    private IMallFeedbackService feedbackService;
    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;

    /**
     * 添加反馈
     */
    @PostMapping("save")
    public Object save(String userName) {
        JSONObject feedbackJson = this.getJsonRequest();
        if (null != feedbackJson) {
            MallFeedbackEntity feedbackVo = new MallFeedbackEntity();
            feedbackVo.setUserId(SecurityUtils.getUserId());
            feedbackVo.setUserName(userName);
            feedbackVo.setMobile(feedbackJson.getString("mobile"));
            feedbackVo.setFeedType(feedbackJson.getInteger("index"));
            feedbackVo.setStatus(1);
            feedbackVo.setContent(feedbackJson.getString("content"));
            feedbackVo.setAddTime(new Date());
            feedbackService.save(feedbackVo);
            return AjaxResult.success("感谢你的反馈");
        }
        return AjaxResult.error("反馈失败");
    }

    public JSONObject getJsonRequest() {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
